package com.catering.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.catering.dao.YqEnumChildDao;
import com.catering.entity.enums.YqEnumChild;
import com.catering.service.utils.UntilService;
import com.catering.until.CommonUtils;
import com.catering.until.ResultData;
import com.catering.until.ResultEnum;
import com.catering.until.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Service
@Slf4j
public class UntilServiceImpl implements UntilService {
	

    @Value("${file.upload-dir}")
	private String filepath;
	@Autowired
	private FileService fileService;
	@Autowired
	private YqEnumChildDao childDao;

	public Map filePath(String fileType) {
		String outputFileName = null,outputFilePath = null,imgUrl = null;
		outputFileName = CommonUtils.getUuid()+".jpg";
		if(fileType.equals("0")) {  //0上传头像
			outputFilePath = filepath;//确定文件存储位置
			imgUrl = outputFileName;
		}else {
			outputFilePath = filepath;
			imgUrl = outputFileName ;
		}
		String desPath = outputFilePath +  outputFileName;
		Map map = new HashMap();
		map.put("outputFileName", outputFileName);
		map.put("outputFilePath", outputFilePath);
		map.put("imgUrl", imgUrl);
		map.put("desPath", desPath);
		return map;
	}

	public ResultData saveImg(Map map, MultipartFile multipartFile, String type){
		File file = new File(map.get("outputFilePath").toString());
		if (!file.isDirectory()){
		    file.mkdirs();
		}
		boolean flag = false;
		System.out.println(map);
		try {
			multipartFile.transferTo(new File(file,map.get("outputFileName").toString()));
			if(type.equals("0")) {
				flag = CommonUtils.compressPicForScale(map.get("desPath").toString(), map.get("desPath").toString(), 500, 0.8);
			}else{
				flag = CommonUtils.compressPicForScale(map.get("desPath").toString(), map.get("desPath").toString(), 102400, 0.8);
			}
			if(flag) {
				return ResultData.success(map.get("imgUrl").toString());
			}else {
				return ResultData.error(ResultEnum.UPLOAD_ERROR.getCode(),ResultEnum.UPLOAD_ERROR.getMsg());
			}
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return ResultData.success(map.get("imgUrl").toString());
		//将图片压缩到500kb以下
	}

    /**
     * 后台功能富文本编辑器图片上传
     * @param file
     * @return
     */
    public void uploadImage(MultipartFile[] file,HttpServletResponse response,HttpServletRequest  request){
        response.setCharacterEncoding("UTF-8"); 
        PrintWriter out=null; 
        try { 
        	out = response.getWriter(); 
        } catch (IOException e1) { 
        	e1.printStackTrace(); 
        } 
        //上传目录地址
        String uploadDir = filepath +  "uploadfiles/";
        //如果目录不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdir();
        for (int i = 0; i < file.length; i++){
		    if (null != file[i]){
		      //文件名为随机字符串
		    	String outputFileName = CommonUtils.getUuid()+file[i].getOriginalFilename();
		    	//定义图片保存的路径
		    	log.info("文件名后缀：path={}",file[i].getOriginalFilename());
		    	String path = filepath + outputFileName;
		    	String imgUrl = outputFileName;
		    	Map m = new HashMap();
		    	m.put("outputFileName", outputFileName);
				m.put("outputFilePath", filepath);
				m.put("desPath", path);
				m.put("imgUrl", imgUrl);
		    	log.info("文件上传服务器地址：path={}",path);
		    	saveImg(m, file[i], "1");
		     // 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名   
		        out.println("<script type=\"text/javascript\">");  
		        out.println("window.parent.CKEDITOR.tools.callFunction(1,'" + imgUrl + "','')");  
		        out.println("</script>");   
		    }
		}
    }
	@Override
    public String ueditorUpload(MultipartFile[] file,String type){
    	String result = "";
    	//上传目录地址
    	//如果目录不存在，自动创建文件夹
    	File dir = new File(filepath);
    	if (!dir.exists()) dir.mkdir();
    	for (int i = 0; i < file.length; i++){
    		if (null != file[i]){
				String fileName = fileService.storeFile(file[i],type);
				String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/downloadFile/").path(fileName).toUriString();
				String fileAddr = filepath+"/"+fileName;
				if("0".equals(type)) fileAddr = filepath + "/" + fileName;
    			//文件名为随机字符串
    			String outputFileName = CommonUtils.getUuid()+file[i].getOriginalFilename();
    			//定义图片保存的路径
    			log.info("文件名后缀：path={}",file[i].getOriginalFilename());
    			Map m = new HashMap();
    			m.put("outputFileName", fileName);
    			m.put("outputFilePath", fileDownloadUri);
    			m.put("desPath", fileAddr);
    			m.put("imgUrl", fileName);
    			log.info("文件上传服务器地址：path={}",filepath);
    			// 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名
    			result = "{\n" +
    	                "    \"state\": \"SUCCESS\",\n" +
    	                "    \"url\": \"" + fileName + "\",\n" +
    	                "    \"title\": \"" + outputFileName + "\",\n" +
    	                "    \"original\": \"" + outputFileName + "\"\n" +
    	                "}";
    		}
    	}
    	return result;
    }

	@Override
	public ResultData selectEnums(Map<String, String> map) {
		if(CommonUtils.checkNull(map.get("parentEnumCode"))) return ResultData.error("父类枚举CODE为空");
		try {
			QueryWrapper<YqEnumChild> wrapper = CommonUtils.getKeySet(map, null);
			wrapper.eq("status",0);
			List<YqEnumChild> list = childDao.selectList(wrapper);
			String[] parentCode = map.get("parentEnumCode").split("<->");
			Map<String,Map> resmap = new LinkedHashMap<>();
			for(String s : parentCode){
				Map<String,String> resmap1 = new LinkedHashMap<String,String>();
				for(YqEnumChild sys : list) {
					if(s.equals(sys.getParentEnumCode())) resmap1.put(sys.getEnumCode(),sys.getEnumName());
				}
				resmap.put(s,resmap1);
			}
			return ResultData.success(resmap);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultData.error(ResultEnum.SERVER_ERROR.getCode(),ResultEnum.SERVER_ERROR.getMsg());
		}
	}
}
